'use strict';
const {verifyToken} = require("wx-common")
exports.main = async (event, context) => {
	const db = uniCloud.database();
	const dbCmd = db.command;
	const payload = event.token?verifyToken(event.token):null;
	const action = event.action;
	let dbRes;
	if(action == "create"){
		// 数据库结构设计
		dbRes = await db.collection("address").add({
			owner:payload.openid,
			name:event.name,
			phone:event.phone,//电话
			address:event.address,//地址
			geopoint:new db.Geo.Point(event.longitude,event.latitude)//经纬度
		})
	}else if(action == "listmy"){
		dbRes = await db.collection("address").where({
			owner:dbCmd.eq(payload.openid)
			})
			.orderBy("_id","desc")//根据id排序
			.get()
	}else if(action == "delete"){
		dbRes = await db.collection("address").where({
			_id:dbCmd.eq(event._id),
			owner:dbCmd.eq(payload.openid)
		}).remove()
	}else if(action=="get"){
		dbRes = await db.collection('address').where({
			_id:dbCmd.eq(event._id)
		})
		.limit(1)
		.get()
	}else if(action=="update"){
		dbRes = await db.collection("address").where({
			_id:dbCmd.eq(event._id),
			owner:dbCmd.eq(payload.openid)
		}).limit(1).update({
			name:event.name,
			phone:event.phone,
			address:event.address,
			geopoint:new db.Geo.Point(event.longitude, event.latitude)
		})
	}
	//返回数据给客户端
	return dbRes?dbRes.data:null;
};
